let db = require("../db/db")
let rights_handler = require("./rights_handler")

rights_handler.set_db(db);

let handle = async function (action, data, login_info, req, res) {
	switch (action) {
		case "build":
			let user_id = login_info.user_id;
			let tree = data.tree;
			let tables = [];
			for (let node of tree) {
				tables.push(node.table_name);
			}
			let has = rights_handler.has_right_of_all_tables("查", tables, user_id);
			if (!has) {
				return (Error("此数据树中至少一个表没有查询权限:" + tables.join(","))); return;
			}
			let sub_trees = [];
			let sub_tree = null;
			for (let i in tree) {
				let node = tree[i];
				node._index = i;
				if (node.circle_parent_field) {
					sub_tree = {
						"circle": true,
						"node": node
					}
					sub_trees.push(sub_tree);
					sub_tree = null;
				}
				else {
					if (sub_tree == null) {
						sub_tree = { "nodes": [node] }
						sub_trees.push(sub_tree);
					}
					else {
						sub_tree.nodes.push(node);
					}
				}
			}
			let sql = "";
			for (let k in sub_trees) {
				let sub_tree = sub_trees[k];
				if (sub_tree.circle) {
					let node = sub_tree.node;
					let i = node._index;
					let extras = node.extras;
					let sql_extras_select = ""
					if (extras) {
						for (let f of extras) {
							sql_extras_select += " ," + db.escapeId(f);
						}
					}
					let sql_parent = "";
					if (node.parent_field) sql_parent = db.escapeId(node.parent_field) + " as parent ,";
					let sql_value = "";
					if (k == sub_trees.length - 1) sql_value = db.escapeId(node.this_field) + " as value ,"; //最后一组自循环为叶子	
					let sql_where = " where is_deleted=0 ";
					if(node.filterby){
						sql_where+=" and "+db.escapeId(node.filterby)+"="+db.escape(node.filtervalue);
					}
					let sql_orderby = " order by " + db.escapeId(node.this_field);
					if(node.orderby){
						sql_orderby = " order by " + db.escapeId(node.orderby) + " "+ (node.orderdir=="desc"?" desc":"");
					}
					sql += "select " + db.escapeId(node.circle_parent_field) + " as circle_parent," + sql_value + sql_parent +
						db.escapeId(node.this_field) + " as t" + i + "_value ," + db.escapeId(node.label_field) + " as label " + sql_extras_select +
						" from " + db.escapeId(node.table_name) + sql_where + sql_orderby + "; ";
				}
				else {
					let sql_select = "select ";
					let sql_from = " from ";
					let sql_where = " where 1=1 ";
					let sql_orderby = " order by ";
					for (let j in sub_tree.nodes) {
						let node = sub_tree.nodes[j];
						let i = node._index;
						let extras = node.extras;
						if (node.parent_field) sql_select += " t" + i + "." + db.escapeId(node.parent_field) + " as t" + i + "_parent,";
						sql_select += " t" + i + "." + db.escapeId(node.this_field) + " as t" + i + "_value ,t" + i + "." + db.escapeId(node.label_field) + " as  t" + i + "_label";
						if (extras) {
							for (let f of extras) {
								sql_select += " ,t" + i + "." + db.escapeId(f) + " as t" + i + "_" + f;
							}
						}
						if (j == 0) {
							sql_from += " " + db.escapeId(node.table_name) + " t" + i;
						}
						else {
							sql_from += " left outer join " + db.escapeId(node.table_name) + " t" + i + " on t" + (i - 1) + "." + db.escapeId(node.this_field) + "=t" + i + "." + db.escapeId(node.parent_field);
						}
						sql_where += " and t" + i + "." + db.escapeId(node.this_field) + " is not null and t" + i + ".is_deleted=0";
						if(node.filterby){
							sql_where+=" and t" + i + "."+ db.escapeId(node.filterby)+"="+db.escape(node.filtervalue);
						}
						if(node.orderby){
							sql_orderby += " t" + i + "." + db.escapeId(node.orderby) + " "+ (node.orderdir=="desc"?" desc":"");
						}
						else{
							sql_orderby += " t" + i + "." + db.escapeId(node.this_field);
						}
						if (j < sub_tree.nodes.length - 1) {
							sql_select += ",";
							sql_orderby += ",";
						}
					}
					let sub_sql = sql_select + sql_from + sql_where + sql_orderby;
					sql += sub_sql + "; ";
				}
			}
			let results = await db.multiquery(sql, []);
			let tree_all = [];
			for (let j in sub_trees) {
				let sub_tree = sub_trees[j];
				let rows = results.rows;
				if (sub_trees.length > 1) {
					rows = results.rows[j];
				}
				let tree_part = [];
				if (sub_tree.circle) { //自循环子树
					let leveled_set = {
						parent_field: "circle_parent",
						field: "t" + sub_tree.node._index + "_value"
					}
					tree_part = find_leveled_children(rows, leveled_set);
				}
				else { //非循环子树
					for (let row of rows) {
						let current = tree_part;
						let keys = Object.keys(row).filter(k => k.substr(k.length - 5) == "value");
						for (let i in keys) {
							let key = keys[i];
							let prefix = key.substr(0, key.length - 6);
							let node = tree[parseInt(prefix.substr(1))];
							let extras = node.extras;
							let find = current.filter(n => n.key == prefix + "_" + row[key]);
							if (find.length > 0) {
								current = find[0].children;
							}
							else {
								let tree_item = {
									parent: row[prefix + "_parent"],
									label: row[prefix + "_label"],
									key: prefix + "_" + row[key],
									value: (j == sub_trees.length - 1 && i == keys.length - 1) ? row[key] : undefined, //最后一个子树的最后一个节点带value
									children: []
								};
								if (extras) {
									for (let f of extras) {
										tree_item[f] = row[prefix + "_" + f];
									}
								}
								current.push(tree_item);
								current = current[current.length - 1].children;
							}

						}
					}
				}
				//嫁接到总树
				if (tree_part && tree_part.length > 0) {
					if (tree_all.length == 0) tree_all = tree_part;
					else {
						let parent_index = sub_tree.node ? sub_tree.node._index - 1 : sub_tree.nodes[0]._index - 1;
						for (let row of tree_part) {
							let parent = find_parent(tree_all, "t" + parent_index + "_value", row.parent);
							if (parent) {
								if (!parent.children || parent.children.length == 0) {
									parent.children = [row];
								}
								else {
									parent.children.push(row);
								}
							}
						}
					}
				}
			}
			return (tree_all);
			break;
		default:
			return (Error('未知的action:' + action));
	}
}

//从总树中找parent
function find_parent(tree, key, parent) {
	for (let row of tree) {
		if (row[key] && row[key] == parent) {
			return row;
		}
		else {
			if (row.children) {
				let find = find_parent(row.children, key, parent);
				if (find) return find;
			}
		}
	}
}

//迭代层级结果
function find_leveled_children(rows, leveled_set, parent) {
	let children = [];
	if (!parent) { //首级节点条件是没有‘节点与这个父节点对应’
		children = rows.filter(item => {
			let parent = item[leveled_set.parent_field];
			return rows.filter(item2 => item2[leveled_set.field] == parent).length == 0;
		});
	}
	else {
		children = rows.filter(item => item[leveled_set.parent_field] == parent);
	}
	children.forEach(item => {
		let grand_children = find_leveled_children(rows, leveled_set, item[leveled_set.field]);
		if (grand_children.length > 0) { item.children = grand_children; }
	})
	return children;
}

module.exports = { handle, find_leveled_children };